package wiki.hitime.stl.daq.util;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import wiki.hitime.stl.daq.bean.base.SyUser;

/**
 * @author zhangdaoping
 * @create 2018/1/23 下午2:19
 */
@Component
public class UserContextUtil {

    private static ThreadLocal<SyUser> threadLocal = new ThreadLocal<>();

    private static final String TOKEN_BEARER = "Bearer ";

    public synchronized static SyUser getUser() {
        return threadLocal.get();
    }

    public synchronized static void setUser(SyUser syUser) {
        threadLocal.set(syUser);
    }

    /**
     * 转换登录用户信息为当期系统用户信息
     *
     * @param headerValue
     */
    public synchronized static boolean setUser(String headerValue) {
        // 此处可以进行用户校验
//        if (StringUtils.isEmpty(headerValue)) {
//            return false;
//        }
//        if (headerValue.startsWith(TOKEN_BEARER)) {
//            headerValue = headerValue.substring(TOKEN_BEARER.length());
//        }
//        if (headerValue.startsWith("\"")) {
//            headerValue = headerValue.replace("\"", "");
//        }
        SyUser syUser = new SyUser();
        syUser.setId(1);
        syUser.setJobNumber("L00001");
        syUser.setTrueName("测试");
        syUser.setPhone("13811111111");
        threadLocal.set(syUser);
        return true;
    }

    /**
     * 获取用户id
     *
     * @return
     */
    public synchronized static String getJobNumber() {
        SyUser syUser = threadLocal.get();
        if (syUser == null) {
            return null;
        }
        return syUser.getJobNumber();
    }

    /**
     * 获取用户真实姓名
     *
     * @return
     */
    public synchronized static String getTrueName() {
        SyUser syUser = threadLocal.get();
        if (syUser == null) {
            return null;
        }
        return syUser.getTrueName();
    }

    /**
     * 移除线程中用户信息
     */
    public synchronized static void remove() {
        threadLocal.remove();
    }
}
